from writer import Writer
import sys

class HTMLWriter(Writer):
	def __init__(self):
		self.__bold = False
		self.__italic = False
		self.__inlineCode = False
		self.__outputStr = ''

	def finalise(self):
		sys.stdout.write(self.__outputStr)

	def header(self, level, text):
		l = str(level)
		self.outputNL('')
		self.outputNL("<h" + l + ">" + text + "</h" + l + ">")

	def outputNL(self, str):
		""" Puts str in the outputbuffer and
		ends the current line
		"""
		self.__outputStr += str + '\n'
	
	def output(self, str):
		self.__outputStr += str

	def decreaseQuoteLevel(self):
		self.outputNL('')
		self.outputNL("</blockquote>")

	def increaseQuoteLevel(self):
		self.outputNL('')
		self.outputNL("<blockquote>")
		# Start each blockquote with a paragraph
		self.paragraph()

	def toggleBold(self):
		if self.__bold:
			self.output("</b>")
			self.__bold = False
		else:
			self.output("<b>")
			self.__bold = True

	def toggleInlineCode(self):
		if self.__inlineCode:
			self.output("</code>")
			self.__inlineCode = False
		else:
			self.output("<code>")
			self.__inlineCode = True

	def toggleItalic(self):
		if self.__italic:
			self.output("</i>")
			self.__italic = False
		else:
			self.output("<i>")
			self.__italic = True

	def character(self, char):
		self.output(self.htmlencode(char))

	def newline(self):
		self.outputNL('')
		self.outputNL("<br />")

	def paragraph(self):
		self.outputNL('')
		self.outputNL('<p>')

	def startcode(self):
		self.outputNL('')
		self.output('<pre><code>')

	def stopcode(self):
		self.outputNL('</code></pre>')
	
	def line(self, line):
		self.outputNL(self.htmlencode(line))

	def link(self, text, url):
		self.printLink(text, self.htmlencode(url))
		
	def printLink(self, text, loc):
		self.output('<a href="' + loc + '">' + text + '</a>')

	def refLink(self, text, ref):
		self.printLink(text, '<<<{0}>>>'.format(ref))

	def linkLabel(self, id, url):
		self.__outputStr = self.__outputStr.replace('<<<{0}>>>'.format(id),
				self.htmlencode(url))

	def equationchar(self, char):
		self.output(char)

	def beginequation(self):
		self.output('<code class="latex">')

	def endequation(self):
		self.output('</code>')

	def htmlencode(self, str):
		return str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

#h = HTMLWriter()

#h.header(1, "Heelloo")
